package com.cn.kehong.controller;


import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import com.cn.kehong.api.IDepartmentService;
import com.cn.kehong.api.IPersonnelManageService;
import com.cn.kehong.api.IRoleService;
import com.cn.kehong.dao.PersonnelManagementMapper;
import com.cn.kehong.domain.*;
import com.cn.kehong.utils.CommonUtil;
import com.cn.kehong.utils.Constants;
import com.cn.kehong.utils.JsonResponse;
import com.cn.kehong.utils.QueryForm;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created On : 2023/12/12.
 * <p>
 * Author : Huiyan
 * <p>
 * Description: 扩展应用---人事管理----控制层
 */
@Controller
@RequestMapping("/personnelManage")
public class PersonnelManagementController {


    @Autowired
    private IPersonnelManageService personnelManageService;
    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;
    @Autowired
    private PersonnelManagementMapper personnelManagementMapper;

    /**
     * @author : Huiyan feng
     * @date   : 2023/12/13
     * @param  : [queryForm, frontToken]
     * @description : 人事办理  仅显示3个月内的在职
     */
    @RequestMapping("/getCurrentPersonnelList/{frontToken}")
    @ResponseBody
    public JsonResponse<List<PersonnelManagement>> getCurrentPersonnelList(@RequestBody QueryForm queryForm, @PathVariable(value = "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<List<PersonnelManagement>> response = new JsonResponse<>();
        List<PersonnelManagement> personnelManagements = personnelManageService.getCurrentPersonnelList(queryForm);
        response.setResult(personnelManagements);
        response.setSuccess(true);
        return response;
    }

    /**
     * @author : Huiyan feng
     * @date   : 2023/12/13
     * @param  : [queryForm, frontToken]
     * @description : 查询统计
     */
    @RequestMapping("/getAllPersonnelList/{frontToken}")
    @ResponseBody
    public JsonResponse<List<PersonnelManagement>> getAllPersonnelList(@RequestBody QueryForm queryForm,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<List<PersonnelManagement>> response = new JsonResponse<>();
        List<PersonnelManagement> personnelManagements = personnelManageService.getAllPersonnelList(queryForm);
        response.setResult(personnelManagements);
        response.setSuccess(true);
        return response;
    }

    @RequestMapping("/getSelectPersonnelList/{frontToken}")
    @ResponseBody
    public JsonResponse<List<PersonnelManagement>> getSelectPersonnelList( @PathVariable(value = "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<List<PersonnelManagement>> response = new JsonResponse<>();
        List<PersonnelManagement> personnelManagements = personnelManageService.getSelectPersonnelList();
        response.setResult(personnelManagements);
        response.setSuccess(true);
        return response;
    }


    /**
     * @author : Huiyan feng
     * @date   : 2023/12/13
     * @param  : [personnelManagement, frontToken]
     * @description : 员工注册
     */
    @RequestMapping("/addPersonnelManagement/{frontToken}")
    @ResponseBody
    public JsonResponse<String> addPersonnelManagement(@RequestBody PersonnelManagement personnelManagement,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<String> response = new JsonResponse<>();
        String result = personnelManageService.addPersonnelManagement(personnelManagement);
        return CommonUtil.getResponseData(response,result);
    }


    /**
     * @author : Huiyan feng
     * @date   : 2023/12/13
     * @param  : [personnelManagement, frontToken]
     * @description : 修改员工信息
     */
    @RequestMapping("/updatePersonnelManagement/{frontToken}")
    @ResponseBody
    public JsonResponse<String> updatePersonnelManagement(@RequestBody PersonnelManagement personnelManagement,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<String> response = new JsonResponse<>();
        String result = personnelManageService.updatePersonnelManagement(personnelManagement);
        return CommonUtil.getResponseData(response,result);
    }


    @RequestMapping("/deletePersonnelManagement/{frontToken}")
    @ResponseBody
    public JsonResponse<String> deletePersonnelManagement(@RequestBody QueryForm queryForm,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<String> response = new JsonResponse<>();
        String result = personnelManageService.deletePersonnelManagement(queryForm);
        return CommonUtil.getResponseData(response,result);
    }

    //操作工
    @RequestMapping("/getPersonnelIdAndName/{frontToken}")
    @ResponseBody
    public JsonResponse<List<PersonnelManagement>> getPersonnelIdAndName(@RequestBody QueryForm queryForm,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<List<PersonnelManagement>> response = new JsonResponse<>();
        List<PersonnelManagement> list = personnelManageService.getPersonnelIdAndName(queryForm);
        response.setResult(list);
        response.setSuccess(true);
        return response;
    }


    //首页--人事与检疫
    @RequestMapping("/countPersonnelAndHealth/{frontToken}")
    @ResponseBody
    public JsonResponse<Map<String,Integer>> countPersonnelAndHealth(@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<Map<String,Integer>> response = new JsonResponse<>();
        Map<String,Integer> map = personnelManageService.countPersonnelAndHealth();
        response.setResult(map);
        response.setSuccess(true);
        return  response;
    }


    @RequestMapping("/addPerson/{frontToken}")
    @ResponseBody
    public JsonResponse<String> addPerson(@RequestBody List<PersonnelManagement> personnelManagements, @PathVariable(value = "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<String> response = new JsonResponse<>();
        String result = personnelManageService.addPerson(personnelManagements);
        return CommonUtil.getResponseData(response,result);
    }

    @RequestMapping("/updatePerson/{frontToken}")
    @ResponseBody
    public JsonResponse<String> updatePerson(@RequestBody PersonnelManagement personnelManagement, @PathVariable(value = "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<String> response = new JsonResponse<>();
        String result = personnelManageService.updatePerson(personnelManagement);
        return CommonUtil.getResponseData(response,result);
    }


    @RequestMapping("/getPersonnelList/{frontToken}")
    @ResponseBody
    public JsonResponse<List<PersonnelManagement>> getPersonnelList(@RequestBody QueryForm queryForm, @PathVariable(value = "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<List<PersonnelManagement>> response = new JsonResponse<>();
        List<PersonnelManagement> personnelManagements = personnelManageService.getPersonnelList(queryForm);
        response.setResult(personnelManagements);
        response.setSuccess(true);
        return response;
    }

    //人员模版下载
    @ResponseBody
    @RequestMapping("/downloadPersonTempFile")
    public void downloadPersonTempFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String path = request.getSession().getServletContext().getRealPath("/WEB-INF/classes/");
        String fileName = path + "person.xlsx";
        this.downloadFile(fileName,response);
    }
    public void downloadFile(String path, HttpServletResponse response) throws Exception {
        String name = StringUtils.isNotBlank(path)?path:"";
        name = URLDecoder.decode(name,"utf-8");
        name = new String(name.getBytes("ISO-8859-1"),"utf-8");
        InputStream is = null;
        OutputStream os = null;
        try {
            File file = new File(name);
            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "utf-8"));
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            is = new FileInputStream(file);
            os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            closeInputStream(is);
            closeOutputStream(os);
        }
    }

    private static void closeInputStream(InputStream is) {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void closeOutputStream(OutputStream os) {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //人员管理模版导入
    @ResponseBody
    @RequestMapping("/importPersonTempFile")
    public JsonResponse<String> importPersonTempFile(@RequestParam(value = "multipartFile", required = true) MultipartFile multipartFile, @RequestParam(value ="notToken", required = true) String notToken) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        DataFormatter formatter = new DataFormatter();

        try{
            InputStream is=multipartFile.getInputStream();
            XSSFWorkbook wb=new XSSFWorkbook(is);
            XSSFSheet sheet = wb.getSheetAt(0); // 获取第一个工作表
            XSSFRow row=null;
            XSSFCell cell=null;
            PersonnelManagement personnelManagement=null;
            List<PersonnelManagement> personnelManagementArrayList=new ArrayList<>();
            int num=1;
            for (int i=1;i<=sheet.getLastRowNum();i++){
                row=sheet.getRow(i);
                personnelManagement = new PersonnelManagement();
                String id = CommonUtil.generateRandomNum("worker_");
                personnelManagement.setId(id);
                personnelManagement.setStatus("0");
                personnelManagement.setCreateTime(new Date());
                personnelManagement.setUpdateTime(new Date());
                for (int j=0;j<row.getLastCellNum();j++){
                    cell=row.getCell(j);
                    String cellValue = formatter.formatCellValue(cell);
                    if (j==0){
                        List<Department> department=departmentService.getIdBydeptName(cellValue);
                        if (department.size()==0){
                            response.setMessage("第"+num+"行"+"部门不存在，请检查部门");
                            return response;
                        }else {
                            personnelManagement.setDeptId(department.get(0).getId());
                        }
                    }else if (j==1){
                        List<Role> roles=roleService.getIdByRoleName(cellValue);
                        if (roles.size()==0){
                            response.setMessage("第"+num+"行"+"角色不存在，请检查角色");
                            return response;
                        }else {
                            personnelManagement.setJobCategory(roles.get(0).getId());
                        }
                    }else if(j==2){
                        if (this.countEqName(cellValue,id) > 0){
                            response.setMessage("第"+num+"行"+"人员已经存在，请检查人员");
                            return response;
                        }else {
                            personnelManagement.setEmployeeName(cellValue);
                        }
                    }else if(j==3){
                        personnelManagement.setJobNumber(cellValue);
                        personnelManagement.setCreateUserId("admin");
                    }else if (j==4){
                        SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy/M/d");
                        SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = originalFormat.parse(cellValue);
                        String formattedDateStr = targetFormat.format(date);
                        personnelManagement.setJoinedDate(formattedDateStr);
                    }
                }
                personnelManagementArrayList.add(personnelManagement);
                num++;
            }
            int ret = personnelManagementMapper.batchInsertPerson(personnelManagementArrayList);
            if (ret!=0){
                response.setSuccess(true);
                return response;
            }
        }catch (Exception e){
            e.printStackTrace();
            response.setMessage("系统忙，请稍后重试....");
        }
        return response;
    }

    private int countEqName(String name,String id) {
        PersonnelManagementExample managementExample = new PersonnelManagementExample();
        PersonnelManagementExample.Criteria criteria = managementExample.createCriteria();

        criteria.andStatusNotEqualTo(Constants.DEL_STATUS).andEmployeeNameEqualTo(name);
        if (StringUtils.isNotEmpty(id)){
            criteria.andIdNotEqualTo(id);
        }

        int count = personnelManagementMapper.countByExample(managementExample);
        return count;
    }


}
